<template>
  <div class="overview" style="width: 80%; margin: auto">
    <n-space justify="space-between" style="margin-bottom: 1vh">
      <n-h2>问卷填写记录总览</n-h2>
      <n-space>
        <n-button type="error" ghost @click="deleteAnswers"
          >清除答卷数据</n-button
        >
        <div style="display: inline-block; width: 1%"></div>
        <n-button type="primary" @click="exportQ" ghost>导出答卷数据</n-button>
      </n-space>
    </n-space>
    <n-data-table
      :columns="columns"
      :data="listData"
      :pagination="pagination"
    />
    <n-modal
      class="custom-card"
      v-model:show="showModal"
      preset="card"
      :title="
        '作答预览--' +
        title +
        (totalScore && totalScore >= 0 ? ' (总分：' + totalScore + '分)' : '')
      "
      size="huge"
      :bordered="false"
      style="width: 50vw; margin: 0 auto"
      id="modal"
    >
      <!-- 右上 -->
      <template #header-extra>
        <div v-show="showOpt">
          <n-button circle style="margin-right: 2vw" @click="printResult">
            <n-icon size="25">
              <PrintIconO />
            </n-icon>
          </n-button>
        </div>
      </template>
      <n-statistic label="显示设置" v-show="showOpt">
        <n-space>
          <n-checkbox v-model:checked="showIndex"> 显示题号 </n-checkbox>
          <n-checkbox v-model:checked="onlyAnswer"> 只显示回答 </n-checkbox>
          <n-checkbox v-model:checked="showDetail">
            显示所有原题选项
          </n-checkbox>
          <n-checkbox v-model:checked="showSkip"> 显示跳过题目 </n-checkbox>
          <n-checkbox v-model:checked="showGap"> 显示间隔 </n-checkbox>
        </n-space>
      </n-statistic>
      <n-card>
        <n-form label-placement="left" size="small" :show-feedback="false">
          <n-space>
            <n-form-item label="序号" style="min-width: 20vw">
              {{ tempNumber }}
            </n-form-item>
            <n-form-item label="提交时间" style="min-width: 20vw">
              {{ tempSubmitTime }}
            </n-form-item>
          </n-space>
          <n-space>
            <n-form-item label="用时" style="min-width: 20vw">
              {{ tempDuration }}
            </n-form-item>
            <n-form-item label="来源" style="min-width: 20vw">
              {{ tempIP }}
            </n-form-item>
          </n-space>
        </n-form>
      </n-card>
      <template #footer>
        <div
          v-for="(q, index) in qArray"
          :key="
            q.id +
            '-' +
            ((onlyAnswer ? 1 : 0) +
              (showSkip ? 1 : 0) +
              (showDetail ? 1 : 0) +
              (showIndex ? 1 : 0))
          "
        >
          <div v-if="showSkip || !isEmpty(q)">
            <fill-q
              :index="showIndex ? index + 1 : 0"
              :title="q['title']"
              :remark="q['remark']"
              :required="q['required']"
              :fill="q['more']['fill']"
              v-if="q['type'] === 'q-fill'"
              :onlyAnswer="onlyAnswer"
            ></fill-q>
            <single-q
              :index="showIndex ? index + 1 : 0"
              :title="q['title']"
              :remark="q['remark']"
              :required="q['required']"
              :options="q['more']['options']"
              :option="q['more']['option']"
              :showDetail="showDetail"
              :onlyAnswer="onlyAnswer"
              v-if="q['type'] === 'q-s'"
            ></single-q>
            <multi-q
              :index="showIndex ? index + 1 : 0"
              :title="q['title']"
              :remark="q['remark']"
              :required="q['required']"
              :options="q['more']['options']"
              :optionsSelect="q['more']['optionsSelect']"
              :showDetail="showDetail"
              :onlyAnswer="onlyAnswer"
              v-if="q['type'] === 'q-m'"
            ></multi-q>
            <rate-q
              :index="showIndex ? index + 1 : 0"
              :title="q['title']"
              :remark="q['remark']"
              :required="q['required']"
              :rate="q['more']['rate']"
              :value="q['more']['value']"
              v-if="q['type'] === 'q-rate'"
              :onlyAnswer="onlyAnswer"
            ></rate-q>
            <locate-q
              :index="showIndex ? index + 1 : 0"
              :title="q['title']"
              :remark="q['remark']"
              :required="q['required']"
              :locate="q['more']['locate']"
              v-if="q['type'] === 'q-locate'"
              :onlyAnswer="onlyAnswer"
            ></locate-q>
            <fill-e-q
              :index="showIndex ? index + 1 : 0"
              :title="q['title']"
              :remark="q['remark']"
              :required="q['required']"
              :score="q['more']['actualScore']"
              :fill="q['more']['fill']"
              v-if="q['type'] === 'eq-fill'"
              :onlyAnswer="onlyAnswer"
            ></fill-e-q>
            <single-e-q
              :index="showIndex ? index + 1 : 0"
              :title="q['title']"
              :remark="q['remark']"
              :required="q['required']"
              :score="q['more']['actualScore']"
              :options="q['more']['options']"
              :option="q['more']['option']"
              :showDetail="showDetail"
              :onlyAnswer="onlyAnswer"
              v-if="q['type'] === 'eq-s'"
            ></single-e-q>
            <multi-e-q
              :index="showIndex ? index + 1 : 0"
              :title="q['title']"
              :remark="q['remark']"
              :required="q['required']"
              :score="q['more']['actualScore']"
              :options="q['more']['options']"
              :optionsSelect="q['more']['optionsSelect']"
              :showDetail="showDetail"
              :onlyAnswer="onlyAnswer"
              v-if="q['type'] === 'eq-m'"
            ></multi-e-q>
            <apply-q
              :index="showIndex ? index + 1 : 0"
              :title="q['title']"
              :remark="q['remark']"
              :required="q['required']"
              :options="q['more']['options']"
              :option="q['more']['option']"
              :showDetail="showDetail"
              :onlyAnswer="onlyAnswer"
              v-if="q['type'] === 'q-apply'"
            ></apply-q>
            <n-divider v-if="showGap"></n-divider>
          </div>
        </div>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import {
  PrintOutline as PrintIconO,
  ArrowBackOutline as LeftIconO,
  ArrowForwardOutline as RightIconO,
} from '@vicons/ionicons5';
import MultiQ from './components/NormalQuestion/MultiChoiceQ.vue';
import FillQ from './components/NormalQuestion/FillQ.vue';
import RateQ from './components/NormalQuestion/RateQ.vue';
import { NIcon } from 'naive-ui';
import SingleQ from './components/NormalQuestion/SingleChoiceQ.vue';
import { Delete } from '@vicons/carbon';
import { EyeOutline } from '@vicons/ionicons5';
import LocateQ from './components/NormalQuestion/LocationQ.vue';
import ApplyQ from './components/SpecialQuestion/ApplyQ.vue';
import FillEQ from './components/ExamQuestion/FillEQ.vue';
import MultiEQ from './components/ExamQuestion/MultiChoiceEQ.vue';
import SingleEQ from './components/ExamQuestion/SingleChoiceEQ.vue';
import { Clean } from '@vicons/carbon';
import {
  ref,
  h,
  computed,
  watch,
  reactive,
  onMounted,
  getCurrentInstance,
} from 'vue';
import { Ques } from '@api/question';
import { useMessage } from 'naive-ui';
import { FileExport, Notebook } from '@vicons/tabler';
const message = useMessage();
const exportQ = () => {
  window.open(
    'http://59.110.170.162:8090/api/q/analysis/download?questionnaireId=' +
      props.id
  );
};

const props = defineProps({
  id: {
    type: String,
    required: true,
  },
});
//清空答卷
const deleteAnswers = () => {
  Ques.deleteAnswer({ qId: Number(props.id) })
    .then((res: any) => {
      if (res.data.status == 200) {
        listData.value = [];
        message.success('清除成功！');
      } else if (res.data.status == 400) {
      } else {
        message.error('出错了，请联系管理员');
      }
    })
    .catch((error: any) => {
      message.error(error);
    });
};
// 问卷预览
const showModal = ref(false);

// 显示题号
const showIndex = ref(true);
// 是否显示题目
const onlyAnswer = ref(false);
// 是否显示跳过的题目
const showSkip = ref(false);
// 是否显示原题目选项等
const showDetail = ref(false);
// 显示间隔
const showGap = ref(true);

// 显示上一条

// 显示下一题

// 打印结果
const showOpt = ref(true);
let back;
let modal;
function printPre() {
  showOpt.value = false;
}
function printPre2() {
  // back = window.document.body.innerHTML;
  // modal = document.getElementById('modal').innerHTML;
}
async function printResult() {
  try {
    let n = await Promise.all([printPre(), printPre2]).then(() => {
      // window.document.body.innerHTML = modal;
    });
    console.log(n);
    window.print();
  } catch (error) {
    console.log(error);
  } finally {
    showOpt.value = true;
  }
}
// function printResult (){

//   // let newstr = proxy.$refs.modal.innerHTML;
//   // let oldstr = document.body.innerHTML;
//   // document.body.innerHTML = newstr;
//   let modal = document.getElementById('modal').innerHTML;
//   let back = window.document.body.innerHTML;
//   window.document.body.innerHTML = modal;
//   //调用打印功能
//   window.print();
//   window.document.body.innerHTML = back; //重新给页面内容赋值；
//   // new Promise(() => {
//   //   window.print();
//   // }).then(() => {
//   //   showOpt.value = true;
//   // });
//   // document.body.innerHTML = oldstr;
// };

// 判断题目是否为空
const isEmpty = (q: any) => {
  switch (q.type) {
    case 'q-s':
      if (!q.more.option) {
        return true;
      } else {
        return false;
      }
    case 'q-m':
      if (!q.more.optionsSelect) {
        return true;
      } else {
        return false;
      }
    case 'q-fill':
      if (!q.more.fill) {
        return true;
      } else {
        return false;
      }
    case 'q-rate':
      if (!q.more.value) {
        return true;
      } else {
        return false;
      }
    case 'q-locate':
      if (!q.more.locate) {
        return true;
      } else {
        return false;
      }
    case 'q-apply':
      if (!q.more.option) {
        return true;
      } else {
        return false;
      }
    case 'eq-s':
      if (!q.more.option) {
        return true;
      } else {
        return false;
      }
    case 'eq-m':
      if (!q.more.optionsSelect) {
        return true;
      } else {
        return false;
      }
    case 'eq-fill':
      if (!q.more.fill) {
        return true;
      } else {
        return false;
      }
  }
};

const qArray = ref([]);
function findIndex(number: number) {
  let found = listData.value.length;
  let index = 0;
  while (index < found) {
    if (listData.value[index].number === number) {
      return index;
    }
    index++;
  }
  return -1;
}
const tempIndex = ref(-1);
const tempNumber = ref(-1);
const tempDuration = ref('');
const tempSubmitTime = ref('');
const tempIP = ref('');

const title = ref('');
const totalScore = ref(-1);
const listData = ref([]);
onMounted(() => {
  console.log('获取答卷列表');
  console.log(props.id);

  listData.value.splice(0, columns.length);
  Ques.overviewQ({ id: Number(props.id) })
    .then((res: any) => {
      console.log(res);
      if (res.data.status == 200) {
        listData.value = res.data.data.data;
        title.value = res.data.data.title;
      } else if (res.data.status == 400) {
      } else {
        message.error('出错了，请联系管理员');
      }
    })
    .catch((error: any) => {
      message.error(error);
    });
});
const pagination = {
  pageSize: 10,
};
const dele = (rowData: object, rowIndex: number) => {
  return h(
    'button',
    {
      style: 'background: rgba(1, 1, 1, 0);border:none;cursor: pointer;',
      onClick: () => {
        console.log('我要删除了');
        Ques.deleteAnswer({ id: Number((rowData as any).aId) })
          .then((res: any) => {
            console.log(res);
            if (res.data.status == 200) {
              //调用获取最新答卷列表
              Ques.overviewQ({ id: Number(props.id) })
                .then((res: any) => {
                  if (res.data.status == 200) {
                    listData.value = res.data.data.data;
                  } else if (res.data.status == 400) {
                    listData.value = [];
                  } else {
                    message.error('出错了，请联系管理员');
                  }
                })
                .catch((error: any) => {
                  message.error(error);
                });

              message.success('清除成功！');
            } else if (res.data.status == 400) {
            } else {
              message.error('出错了，请联系管理员');
            }
          })
          .catch((error: any) => {
            message.error(error);
          });
      },
    },
    h(NIcon, { size: '20' }, h(Delete))
  );
};
const see = (row: any) => {
  // 点击预览
  console.log(row);
  tempNumber.value = row.number;
  tempDuration.value = row.usedTime;
  tempSubmitTime.value = row.submitTime;
  tempIP.value = row.ip;
  tempIndex.value = findIndex(row.number);
  console.log(listData.value[tempIndex.value].aId);
  console.log('aid');
  Ques.answerQ({
    aId: listData.value[tempIndex.value].aId,
  }).then((res: any) => {
    console.log('see');
    console.log(res);
    if (res.data.status === 200) {
      qArray.value = res.data.data.content;
      showModal.value = true;
      totalScore.value = res.data.data.totalScore;
      console.log('totalScore.value: ', totalScore.value);
    } else {
      window.$message.error(res.data.msg);
    }
  });
};

const seePaper = (rowData: object, rowIndex: number) => {
  return h(
    'button',
    {
      style: 'background: rgba(1, 1, 1, 0);border:none;cursor: pointer;',
      onClick: () => {
        see(rowData);
      },
    },
    [h(NIcon, { size: '20' }, h(EyeOutline))]
  );
};

const columns = [
  {
    title: '序号',
    key: 'number',
  },
  {
    title: '开始答卷时间',
    key: 'startTime',
  },
  {
    title: '提交答卷时间',
    key: 'submitTime',
  },
  {
    title: '所用时间',
    key: 'usedTime',
  },
  {
    title: '来源IP(?)',
    key: 'ip',
  },
  {
    title: '查看原卷',
    key: 'see',
    render: seePaper,
  },
  {
    title: '删除',
    key: 'delete',
    render: dele,
  },
];
</script>

<style scoped lang="scss">
.overview {
  border: solid 1px rgb(238, 238, 238);
  border-radius: 1vh;
  background-color: #fff;
  min-height: 60vh;
  box-shadow: 3px 3px 5px #c8c8c8, -3px -3px 5px #ececec;
  padding: 6vh;
}
</style>
